document.addEventListener('DOMContentLoaded', function () {
    let musicPlaying = false;
    let currentVideoIndex = 0;
    let currentPhotoIndex = 0;
    // 视频列表
    let videos = [];
    let photos = []

    function renderVideos() {
        const ticketsContainer = document.getElementById('tickets-container');
        ticketsContainer.innerHTML = '';
        if (!memoriesData || !memoriesData.videos || !memoriesData.videos.length === 0) {
            return;
        }

        // 按ID倒序排序（最新的在前面）
        memoriesData.videos.sort((a, b) => a.id - b.id);
        // 创建祝福卡片
        memoriesData.videos.forEach((t,index) => {
             const isActive = index === 0 ? 'active' : '';
            const videoInfo = document.createElement('div');
            videoInfo.innerHTML = ` <div class="ticket ${isActive}" data-video=${t.ticketNumber}>
            <div class="ticket-stub">
                <div class="ticket-number">${t.ticketNumber}</div>
                <div class="ticket-title">${t.ticketTitle}</div>
                <div class="ticket-subtitle">${t.ticketSubtitle}</div>
            </div>
            <div class="ticket-main">
                <div class="ticket-info">
                    <h3>${t.title}</h3>
                    <p>${t.description}</p>
                    <div class="ticket-details">
                        <span>${t.time}</span>
                        <span>${t.type}</span>
                    </div>
                </div>
            </div>
        </div>
        `;
            ticketsContainer.appendChild(videoInfo);
        });
    }

    function renderPhotos() {
        const photosGrid = document.getElementById('photos-grid');
        photosGrid.innerHTML = '';
        // 如果没有祝福
        if (!memoriesData || !memoriesData.photos || !memoriesData.photos.length === 0) {
            return;
        }
        // 创建祝福卡片
        memoriesData.photos.forEach(t => {
            const videoInfo = document.createElement('div');
            videoInfo.innerHTML = ` <div class="photo-item" data-image="${t.src}">
                <img src="${t.src}" alt="${t.alt}">
                <div class="photo-overlay">
                    <span class="photo-caption">${t.caption}</span>
                </div>
            </div>
        `;
            photosGrid.appendChild(videoInfo);
        });
    }

    function loadMemoriesData() {
        fetch('../data/memories.json')
            .then(response => response.json())
            .then(data => {
                memoriesData = data || [];
                videos = data.videos || [];
                photos = data.photos || [];
                renderVideos();
                renderPhotos();
                addEventListeners();
            });
    }

    loadMemoriesData();

    // 照片列表


    // 音频元素
    const backgroundMusic = document.getElementById('background-music');
    const applauseSound = document.getElementById('applause-sound');
    const musicToggle = document.getElementById('music-toggle');

    // 视频元素
    const mainVideo = document.getElementById('main-video');
    const videoOverlay = document.querySelector('.video-overlay');
    const playButton = document.querySelector('.play-button');

    // 控制元素
    const prevVideoBtn = document.getElementById('prev-video');
    const playPauseBtn = document.getElementById('play-pause');
    const nextVideoBtn = document.getElementById('next-video');
    const volumeToggle = document.getElementById('volume-toggle');
    const volumeSlider = document.getElementById('volume-slider');
    const fullscreenBtn = document.getElementById('fullscreen');

    // 照片查看器
    const photoViewer = document.getElementById('photo-viewer');
    const viewerImage = document.getElementById('viewer-image');
    const viewerCaption = document.querySelector('.viewer-caption');
    const viewerClose = document.querySelector('.viewer-close');
    const viewerPrev = document.getElementById('viewer-prev');
    const viewerNext = document.getElementById('viewer-next');

    // 初始化
    init();

    function init() {
        // 启动粒子系统
        if (typeof initParticles === 'function') {
            initParticles();
        }

        // 尝试自动播放音乐
        tryAutoPlayMusic();

        // 初始化视频
        loadVideo(currentVideoIndex);

        // 添加特殊效果
        addSpecialEffects();
    }

    function tryAutoPlayMusic() {
        const playPromise = backgroundMusic.play();
        if (playPromise !== undefined) {
            playPromise.then(() => {
                musicPlaying = true;
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
            }).catch(() => {
                musicPlaying = false;
                musicToggle.textContent = '🔇';

                // 添加用户交互启动音乐
                document.addEventListener('click', () => {
                    if (!musicPlaying) {
                        backgroundMusic.play().then(() => {
                            musicPlaying = true;
                            musicToggle.textContent = '🎵';
                            musicToggle.style.animation = 'musicPulse 2s infinite';
                        });
                    }
                }, {once: true});
            });
        }
    }

    function addEventListeners() {
        // 音乐控制
        musicToggle.addEventListener('click', toggleMusic);

        // 电影票点击
        document.querySelectorAll('.ticket').forEach((ticket, index) => {
            ticket.addEventListener('click', () => selectVideo(index));
        });

        // 视频控制
        playButton.addEventListener('click', toggleVideoPlay);
        videoOverlay.addEventListener('click', toggleVideoPlay);
        prevVideoBtn.addEventListener('click', () => changeVideo(-1));
        playPauseBtn.addEventListener('click', toggleVideoPlay);
        nextVideoBtn.addEventListener('click', () => changeVideo(1));
        volumeToggle.addEventListener('click', toggleVideoVolume);
        volumeSlider.addEventListener('input', changeVideoVolume);
        fullscreenBtn.addEventListener('click', toggleFullscreen);

        // 视频事件
        mainVideo.addEventListener('play', onVideoPlay);
        mainVideo.addEventListener('pause', onVideoPause);
        mainVideo.addEventListener('ended', onVideoEnded);
        mainVideo.addEventListener('loadstart', onVideoLoadStart);
        mainVideo.addEventListener('canplay', onVideoCanPlay);

        // 照片点击
        document.querySelectorAll('.photo-item').forEach((item, index) => {
            item.addEventListener('click', () => openPhotoViewer(index));
        });

        // 照片查看器控制
        viewerClose.addEventListener('click', closePhotoViewer);
        viewerPrev.addEventListener('click', () => changePhoto(-1));
        viewerNext.addEventListener('click', () => changePhoto(1));
        photoViewer.addEventListener('click', (e) => {
            if (e.target === photoViewer || e.target.classList.contains('viewer-overlay')) {
                closePhotoViewer();
            }
        });

        // 键盘事件
        document.addEventListener('keydown', handleKeyPress);

        // 触摸事件
        addTouchEvents();
    }

    function toggleMusic() {
        if (musicPlaying) {
            backgroundMusic.pause();
            musicToggle.textContent = '🔇';
            musicToggle.style.animation = 'none';
            musicPlaying = false;
        } else {
            backgroundMusic.play().then(() => {
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
                musicPlaying = true;
            }).catch(e => {
                console.log('音乐播放失败:', e);
            });
        }
    }

    function selectVideo(index) {
        if (index === currentVideoIndex) return;

        // 更新票据状态
        document.querySelectorAll('.ticket').forEach((ticket, i) => {
            ticket.classList.toggle('active', i === index);
            if (i === index) {
                ticket.classList.add('selected');
                setTimeout(() => ticket.classList.remove('selected'), 500);
            }
        });

        currentVideoIndex = index;
        loadVideo(index);

        // 创建选择特效
        createSelectionEffect();
    }

    function loadVideo(index) {
        const video = videos[index];
        if (!video) return;

        mainVideo.src = video.src;
        mainVideo.poster = video.poster;
        mainVideo.load();

        // 显示加载状态
        // showVideoLoading();
    }

    function showVideoLoading() {
        const loading = document.createElement('div');
        loading.className = 'video-loading';
        loading.textContent = '加载中';
        document.querySelector('.theater-screen').appendChild(loading);
    }

    function hideVideoLoading() {
        const loading = document.querySelector('.video-loading');
        if (loading) {
            loading.remove();
        }
    }

    function toggleVideoPlay() {
        if (mainVideo.paused) {

            backgroundMusic.pause();
            musicToggle.textContent = '🔇';
            musicToggle.style.animation = 'none';
            musicPlaying = false;

            mainVideo.play().then(() => {
                videoOverlay.classList.add('hidden');
                playPauseBtn.textContent = '▶️';
                document.querySelector('.video-theater').classList.add('playing');
            }).catch(e => {
                console.log('视频播放失败:', e);
            });
        } else {

            backgroundMusic.play().then(() => {
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
                musicPlaying = true;
            }).catch(e => {
                console.log('音乐播放失败:', e);
            });

            mainVideo.pause();
            videoOverlay.classList.remove('hidden');
            playPauseBtn.textContent = '⏸️';
            document.querySelector('.video-theater').classList.remove('playing');
        }
    }

    function changeVideo(direction) {
        const newIndex = (currentVideoIndex + direction + videos.length) % videos.length;
        selectVideo(newIndex);
    }

    function toggleVideoVolume() {
        if (mainVideo.muted) {
            mainVideo.muted = false;
            volumeToggle.textContent = '🔊';
            volumeSlider.value = mainVideo.volume * 100;
        } else {
            mainVideo.muted = true;
            volumeToggle.textContent = '🔇';
        }
    }

    function changeVideoVolume() {
        const volume = volumeSlider.value / 100;
        mainVideo.volume = volume;
        mainVideo.muted = volume === 0;
        volumeToggle.textContent = volume === 0 ? '🔇' : '🔊';
    }

    function toggleFullscreen() {
        if (!document.fullscreenElement) {
            mainVideo.requestFullscreen().catch(e => {
                console.log('全屏失败:', e);
            });
        } else {
            document.exitFullscreen();
        }
    }

    function onVideoPlay() {
        playPauseBtn.textContent = '⏸️';
        videoOverlay.classList.add('hidden');
        document.querySelector('.video-theater').classList.add('playing');
    }

    function onVideoPause() {
        playPauseBtn.textContent = '▶️';
        videoOverlay.classList.remove('hidden');
        document.querySelector('.video-theater').classList.remove('playing');
    }

    function onVideoEnded() {
        // 播放掌声
        if (applauseSound) {
            applauseSound.play().catch(e => console.log('掌声播放失败:', e));
        }

        // 创建掌声特效
        createApplauseEffect();

        // 自动播放下一个视频
        setTimeout(() => {
            changeVideo(1);
        }, 2000);
    }

    function onVideoLoadStart() {
        // showVideoLoading();
    }

    function onVideoCanPlay() {
        hideVideoLoading();
    }

    function createSelectionEffect() {
        // 创建选择特效
        const colors = ['#ff6b9d', '#4ecdc4', '#ffe66d'];

        for (let i = 0; i < 20; i++) {
            const particle = document.createElement('div');
            particle.style.cssText = `
                position: fixed;
                width: 8px;
                height: 8px;
                background: ${colors[Math.floor(Math.random() * colors.length)]};
                border-radius: 50%;
                pointer-events: none;
                z-index: 1000;
                left: ${window.innerWidth / 2}px;
                top: ${window.innerHeight / 2}px;
            `;

            document.body.appendChild(particle);

            const angle = (Math.PI * 2 * i) / 20;
            const distance = 100 + Math.random() * 100;
            const endX = window.innerWidth / 2 + Math.cos(angle) * distance;
            const endY = window.innerHeight / 2 + Math.sin(angle) * distance;

            particle.animate([
                {
                    transform: 'translate(0, 0) scale(1)',
                    opacity: 1
                },
                {
                    transform: `translate(${endX - window.innerWidth / 2}px, ${endY - window.innerHeight / 2}px) scale(0)`,
                    opacity: 0
                }
            ], {
                duration: 1000,
                easing: 'ease-out'
            }).onfinish = () => {
                particle.remove();
            };
        }
    }

    function createApplauseEffect() {
        // 创建掌声特效
        const applauseText = document.createElement('div');
        applauseText.textContent = '👏 精彩！';
        applauseText.style.cssText = `
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            font-size: 48px;
            color: white;
            text-shadow: 0 0 20px rgba(255, 107, 157, 0.8);
            pointer-events: none;
            z-index: 1000;
            font-family: 'Fredoka One', cursive;
        `;

        document.body.appendChild(applauseText);

        applauseText.animate([
            {
                transform: 'translate(-50%, -50%) scale(0)',
                opacity: 0
            },
            {
                transform: 'translate(-50%, -50%) scale(1.2)',
                opacity: 1
            },
            {
                transform: 'translate(-50%, -50%) scale(1)',
                opacity: 1
            },
            {
                transform: 'translate(-50%, -50%) scale(0)',
                opacity: 0
            }
        ], {
            duration: 2000,
            easing: 'ease-out'
        }).onfinish = () => {
            applauseText.remove();
        };
    }

    function openPhotoViewer(index) {
        currentPhotoIndex = index;
        const photo = photos[index];

        viewerImage.src = photo.src;
        viewerCaption.textContent = photo.caption;
        photoViewer.classList.remove('hidden');

        // 添加打开动画
        photoViewer.style.opacity = '0';
        photoViewer.style.transform = 'scale(0.8)';

        requestAnimationFrame(() => {
            photoViewer.style.transition = 'all 0.3s ease';
            photoViewer.style.opacity = '1';
            photoViewer.style.transform = 'scale(1)';
        });
    }

    function closePhotoViewer() {
        photoViewer.style.opacity = '0';
        photoViewer.style.transform = 'scale(0.8)';

        setTimeout(() => {
            photoViewer.classList.add('hidden');
            photoViewer.style.transition = '';
        }, 300);
    }

    function changePhoto(direction) {
        currentPhotoIndex = (currentPhotoIndex + direction + photos.length) % photos.length;
        const photo = photos[currentPhotoIndex];

        // 添加切换动画
        viewerImage.style.opacity = '0';
        viewerImage.style.transform = 'scale(0.9)';

        setTimeout(() => {
            viewerImage.src = photo.src;
            viewerCaption.textContent = photo.caption;

            viewerImage.style.opacity = '1';
            viewerImage.style.transform = 'scale(1)';
        }, 150);
    }

    function handleKeyPress(e) {
        switch (e.key) {
            case ' ':
                e.preventDefault();
                if (photoViewer.classList.contains('hidden')) {
                    toggleVideoPlay();
                } else {
                    closePhotoViewer();
                }
                break;
            case 'Escape':
                if (!photoViewer.classList.contains('hidden')) {
                    closePhotoViewer();
                }
                break;
            case 'ArrowLeft':
                if (!photoViewer.classList.contains('hidden')) {
                    changePhoto(-1);
                } else {
                    changeVideo(-1);
                }
                break;
            case 'ArrowRight':
                if (!photoViewer.classList.contains('hidden')) {
                    changePhoto(1);
                } else {
                    changeVideo(1);
                }
                break;
            case 'f':
            case 'F':
                toggleFullscreen();
                break;
            case 'm':
            case 'M':
                toggleVideoVolume();
                break;
        }
    }

    function addTouchEvents() {
        let touchStartX = 0;
        let touchStartY = 0;

        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        });

        document.addEventListener('touchend', (e) => {
            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;

            const deltaX = touchEndX - touchStartX;
            const deltaY = touchEndY - touchStartY;

            // 水平滑动
            if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                if (!photoViewer.classList.contains('hidden')) {
                    if (deltaX > 0) {
                        changePhoto(-1);
                    } else {
                        changePhoto(1);
                    }
                } else {
                    if (deltaX > 0) {
                        changeVideo(-1);
                    } else {
                        changeVideo(1);
                    }
                }
            }
        });

        // 双击全屏
        let lastTap = 0;
        mainVideo.addEventListener('touchend', (e) => {
            const currentTime = new Date().getTime();
            const tapLength = currentTime - lastTap;

            if (tapLength < 500 && tapLength > 0) {
                toggleFullscreen();
            }

            lastTap = currentTime;
        });
    }

    function addSpecialEffects() {
        // 定期创建电影院氛围粒子
        setInterval(() => {
            if (Math.random() < 0.3) {
                createCinemaParticle();
            }
        }, 3000);

        // 鼠标移动时的光影效果
        // document.addEventListener('mousemove', (e) => {
        //     const theater = document.querySelector('.theater-screen');
        //     if (theater) {
        //         const rect = theater.getBoundingClientRect();
        //         const x = ((e.clientX - rect.left) / rect.width - 0.5) * 20;
        //         const y = ((e.clientY - rect.top) / rect.height - 0.5) * 20;
        //
        //         theater.style.transform = `perspective(1000px) rotateY(${x}deg) rotateX(${-y}deg)`;
        //     }
        // });

        document.addEventListener('mouseleave', () => {
            const theater = document.querySelector('.theater-screen');
            if (theater) {
                theater.style.transform = '';
            }
        });
    }

    function createCinemaParticle() {
        const particle = document.createElement('div');
        particle.style.cssText = `
            position: fixed;
            width: 4px;
            height: 4px;
            background: rgba(255, 255, 255, 0.6);
            border-radius: 50%;
            pointer-events: none;
            z-index: 1;
            left: ${Math.random() * window.innerWidth}px;
            top: ${window.innerHeight + 10}px;
        `;

        document.body.appendChild(particle);

        particle.animate([
            {
                transform: 'translateY(0) rotate(0deg)',
                opacity: 0.6
            },
            {
                transform: `translateY(-${window.innerHeight + 100}px) rotate(360deg)`,
                opacity: 0
            }
        ], {
            duration: 5000 + Math.random() * 3000,
            easing: 'ease-out'
        }).onfinish = () => {
            particle.remove();
        };
    }

    // 页面可见性变化处理
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            if (musicPlaying) {
                backgroundMusic.pause();
            }
            if (!mainVideo.paused) {
                mainVideo.pause();
            }
        } else {
            if (musicPlaying) {
                backgroundMusic.play().catch(e => console.log('恢复播放失败:', e));
            }
        }
    });

    console.log('珍贵回忆页面已加载完成！');
    console.log('操作提示：');
    console.log('- 点击电影票选择视频');
    console.log('- 点击照片查看大图');
    console.log('- 空格键播放/暂停视频');
    console.log('- 左右箭头键切换内容');
    console.log('- F键全屏，M键静音');
    console.log('- ESC键退出查看器');


});

